package com.project.web.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.project.client.domain.UserEntity;
import com.project.client.service.UserService;
import com.project.client.vo.LoginVo;
import com.project.client.vo.RegisterVo;
import com.project.common.annotation.RepeatSubmit;
import com.project.common.core.controller.BaseController;
import com.project.common.core.domain.AjaxResult;
import com.project.common.core.domain.model.LoginClientUser;
import com.project.common.exception.CustomException;
import com.project.common.utils.SecurityUtils;
import com.project.framework.web.service.ClientTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("api/")
public class ClientLoginController extends BaseController {
    @Autowired
    private UserService userService;

    @Autowired
    private ClientTokenService tokenService;

    @RepeatSubmit
    @PostMapping("/login")
    public AjaxResult login(@RequestBody @Validated LoginVo vo) {
        UserEntity entity = userService.selectByUsername(vo.getUsername());
        if (entity == null) {
            throw new CustomException("该帐号未注册");
        } else if (!SecurityUtils.matchesPassword(vo.getPassword(), entity.getPassword())) {
            throw new CustomException("帐号或密码有误");
        }
        LoginClientUser loginUser = new LoginClientUser(entity.getId());
        String token = tokenService.createToken(loginUser);
        JSONObject json = new JSONObject();
        json.put("token", token);
        json.put("username", entity.getUsername());
        return AjaxResult.success(json);
    }

    @RepeatSubmit
    @PostMapping("/register")
    public AjaxResult register(@RequestBody @Validated RegisterVo vo) {
        if (!vo.getPassword().equals(vo.getPassword2())) {
            throw new CustomException("两次密码不一致");
        }
        UserEntity entity = userService.selectByUsername(vo.getUsername());
        if (entity != null) {
            throw new CustomException("该账号已注册");
        }
        entity = new UserEntity();
        entity.setUsername(vo.getUsername());
        entity.setPassword(SecurityUtils.encryptPassword(vo.getPassword()));
        userService.save(entity);
        return AjaxResult.success();
    }
}
